Laravel
Models Migration Relation
Introduction,istallation Strucutre,model,migration Migration,Models,Relation
Les Relations
BelongsTo HasOne HasMany BelongsToMany HasManyThrough
Exemples des Relations
Relations:oneToMany,ManyToMany... Relations:Exemples
Exercices
Exercice 1 Exercice 2
Controllers Views Routes
Routes,Controller,Model,view CRUD: Etudiant CRUD: Car CRUD,Recherche: Book
Validation
Exemple :Projets
Api:Laravel +React
Middleware

Seeders & Factories

Authenfication
Layouts





La relation "HasMany" dans Laravel

Exemple 1
une application de blog, où un article peut avoir plusieurs commentaires. Les tables associées seront articles et comments.
Migration pour la table articles :
 database/migrations/YYYY_MM_DD_create_articles_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id('idArticle'); // Nommer la clé primaire avec idTable
            $table->string('title');
            $table->text('content');
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('articles');
    }
}
Migration pour la table comments :
 database/migrations/YYYY_MM_DD_create_comments_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->id('idComment'); // Nommer la clé primaire avec idTable
            $table->text('content');
            $table->unsignedBigInteger('article_id'); // Clé étrangère

            $table->foreign('article_id')->references('idArticle')->on('articles');
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('comments');
    }
}
Modèle pour la table Article :
 app/Models/Article.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $table = 'articles';
    protected $primaryKey = 'idArticle'; // Nommer la clé primaire avec idTable
    protected $fillable = ['title', 'content'];

    public function comments()
    {
        return $this->hasMany(Comment::class, 'article_id', 'idComment');
    }
}
Modèle pour la table Comment :
 app/Models/Comment.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $table = 'comments';
    protected $primaryKey = 'idComment'; // Nommer la clé primaire avec idTable
    protected $fillable = ['content', 'article_id'];

    public function article()
    {
        return $this->belongsTo(Article::class, 'article_id', 'idArticle');
    }
}
Dans cet exemple, un article (Article) peut avoir plusieurs commentaires (Comment). La clé étrangère article_id dans la table des commentaires fait référence à la clé primaire idArticle dans la table des articles. La méthode comments() dans le modèle Article définit la relation "HasMany", tandis que la méthode article() dans le modèle Comment définit la relation "BelongsTo". Vous pouvez ensuite accéder aux commentaires associés à un article ou à l'article associé à un commentaire de la manière suivante :
Exemple 2
exemple de la relation "HasMany" dans le contexte d'une application de gestion d'une bibliothèque, où chaque auteur peut avoir plusieurs livres. Les tables associées seront authors et books.
Migration pour la table authors :
 database/migrations/YYYY_MM_DD_create_authors_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('authors', function (Blueprint $table) {
            $table->id('idAuthor'); // Nommer la clé primaire avec idTable
            $table->string('name');
            $table->string('nationality');
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('authors');
    }
}
Migration pour la table books :
 database/migrations/YYYY_MM_DD_create_books_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->id('idBook'); // Nommer la clé primaire avec idTable
            $table->string('title');
            $table->text('description');
            $table->unsignedBigInteger('author_id'); // Clé étrangère

            $table->foreign('author_id')->references('idAuthor')->on('authors');
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('books');
    }
}
Modèle pour la table Author :
 app/Models/Author.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Author extends Model
{
    protected $table = 'authors';
    protected $primaryKey = 'idAuthor'; // Nommer la clé primaire avec idTable
    protected $fillable = ['name', 'nationality'];

    public function books()
    {
        return $this->hasMany(Book::class, 'author_id', 'idBook');
    }
}
Modèle pour la table Book :
 app/Models/Book.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    protected $table = 'books';
    protected $primaryKey = 'idBook'; // Nommer la clé primaire avec idTable
    protected $fillable = ['title', 'description', 'author_id'];

    public function author()
    {
        return $this->belongsTo(Author::class, 'author_id', 'idAuthor');
    }
}
Dans cet exemple, chaque auteur (Author) peut avoir plusieurs livres (Book). La clé étrangère author_id dans la table des livres fait référence à la clé primaire idAuthor dans la table des auteurs. La méthode books() dans le modèle Author définit la relation "HasMany", tandis que la méthode author() dans le modèle Book définit la relation "BelongsTo". Vous pouvez ensuite accéder aux livres associés à un auteur ou à l'auteur associé à un livre de la manière suivante :
Exemple 1
exemple de la relation "HasMany" dans le contexte d'une application de gestion d'un magasin en ligne, où chaque catégorie peut avoir plusieurs produits. Les tables associées seront categories et products.
Migration pour la table categories :
 database/migrations/YYYY_MM_DD_create_categories_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id('idCategory'); // Nommer la clé primaire avec idTable
            $table->string('name');
            $table->string('description');
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('categories');
    }
}
Migration pour la table products :
 database/migrations/YYYY_MM_DD_create_products_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id('idProduct'); // Nommer la clé primaire avec idTable
            $table->string('name');
            $table->text('description');
            $table->decimal('price', 8, 2);
            $table->unsignedBigInteger('category_id'); // Clé étrangère

            $table->foreign('category_id')->references('idCategory')->on('categories');
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('products');
    }
}
Modèle pour la table Category :
 app/Models/Category.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table = 'categories';
    protected $primaryKey = 'idCategory'; // Nommer la clé primaire avec idTable
    protected $fillable = ['name', 'description'];

    public function products()
    {
        return $this->hasMany(Product::class, 'category_id', 'idProduct');
    }
}
Modèle pour la table Product :
 app/Models/Product.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'products';
    protected $primaryKey = 'idProduct'; // Nommer la clé primaire avec idTable
    protected $fillable = ['name', 'description', 'price', 'category_id'];

    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id', 'idCategory');
    }
}
Dans cet exemple, chaque catégorie (Category) peut avoir plusieurs produits (Product). La clé étrangère category_id dans la table des produits fait référence à la clé primaire idCategory dans la table des catégories. La méthode products() dans le modèle Category définit la relation "HasMany", tandis que la méthode category() dans le modèle Product définit la relation "BelongsTo".